<template>
  <div>
    <div class="search">
      <input v-model="keyWorld" class="search-input" placeholder="输入城市名/拼音" />
    </div>
    <!-- 数据双向绑定 -->
    <div 
      class="search-Content" 
      ref="search" 
      v-show = "keyWorld"
    >
    <!-- 控制覆盖层显示/不显示  v-show = "keyWorld"-->
      <div>
        <ul>
          <li v-for="(item ,index) in list" :key="index" @click="handleCityClick(item.name)">{{item.name}}</li>
          <!-- 直接判断 .length -->
           <li v-show = "hasNoData">没有匹配到数据</li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import BScroll from "better-scroll";
import {mapMutations} from 'vuex'
window.onload = function() {
  //方法内容
//   $(".search-Content").hide();
};
export default {
  name: "citySearch",
  //计算属性
  computed(){

  },
  data() {
    return {
      keyWorld: "",
      list: [],
      times: null
    };
  },
  props: {
    cities: Object
  },
  created() {},
  methods: {
    handleCityClick(obj){
      // this.$store.commit('change',obj)
      this.change(obj)
      $(".search-Content").fadeOut(500);
      this.keyWorld = null
      this.$router.push('/')
    },
    ...mapMutations(['change']) //简化 this.$store.commit('change',obj)
  },
  watch: {
    keyWorld() {
      if (this.times) {
        clearTimeout(this.times);
      }
      this.times = setTimeout(() => {
        const result = [];
        //循环遍历出城市
        for (let key in this.cities) {
          this.cities[key].forEach(value => {
            //indexOf()检索String是否存在
            if (
              value.name.indexOf(this.keyWorld) > -1 ||
              value.spell.indexOf(this.keyWorld) > -1
            ) {
              result.push(value);
            }
          });
        }
        // this.list = result;

        if (this.keyWorld === "") {
          this.list = [];
        //   $(".search-Content").fadeOut(500);
        } else {
          this.list = result;
        //   $(".search-Content").slideDown(500);
        }
      }, 500);
    }
  },
  //js语法
  mounted() {
    //自定义滚动
    // this.scroll = new BScroll(this.$refs.search)
    this.scroll = new BScroll(this.$refs.search, {
      scrollY: true,
      click: true
    });
  },
//   计算属性
  computed:{
    //   没有匹配到数据
      hasNoData(){
          return !this.list.length
      }
  }
};
</script>
<style scoped>
* {
  touch-action: none;
}
.search {
  overflow: hidden;
  width: 100%;
  height: 35px;
  line-height: 35px;
  text-align: center;
  background: #00bcd4;
}
.search .search-input {
  width: 95%;
  height: 30px;
  line-height: 30px;
  background: #ffffff;
  padding: 0px 5px;
  border: none;
  border-radius: 2px;
  text-align: center;
  color: #666;
}
.search-Content {
  width: 100%;
  height: 100%;
  position: absolute;
  overflow: hidden;
  z-index: 1;
  top: 70px;
  left: 0;
}

.search-Content li {
  line-height: 22px;
  text-indent: 4px;
  border-bottom: 1px dashed #eeeeee;
  background: #ffffff;
}
</style>